<template>
    <div class="smart-table-container">
        <!-- 使用 Element Plus 表格组件 -->
        <el-table ref="tableRef" :data="filteredData" :loading="loading" :height="height" :max-height="maxHeight"
            :stripe="stripe" :border="border" :size="size" :header-cell-style="headerCellStyle" :cell-style="cellStyle"
            @sort-change="handleSortChange" @filter-change="handleFilterChange"
            @selection-change="handleSelectionChange" @row-click="handleRowClick" @row-dblclick="handleRowDblClick"
            style="width: 100%">
            <!-- 选择列 -->
            <el-table-column v-if="showSelection" type="selection" width="55" align="center" fixed="left" />

            <!-- 序号列 -->
            <el-table-column v-if="showIndex" type="index" label="序号" width="80" align="center" fixed="left" />

            <!-- 数据列 -->
            <el-table-column v-for="col in computedColumns" :key="col.key" :prop="col.key"
                :label="col.label || col.title" :width="col.width" :min-width="col.minWidth || 80" :fixed="col.fixed"
                :sortable="col.sortable ? 'custom' : false"
                :filters="col.filterable ? getFilterOptions(col) : undefined"
                :filter-method="col.filterable ? getFilterMethod(col) : undefined"
                :filter-panel="col.filterable && (col.type === 'date' || col.type === 'datetime') ? getDateFilterPanel(col) : undefined"
                :show-overflow-tooltip="col.showOverflowTooltip !== false" :align="col.align || 'left'"
                :header-align="col.headerAlign || col.align || 'left'" :class-name="col.className"
                :label-class-name="col.labelClassName">
                <template #default="{ row, $index }">
                    <!-- 自定义渲染 -->
                    <div v-if="col.render" v-html="col.render(row, $index)"></div>
                    <!-- 标签类型 -->
                    <el-tag v-else-if="col.type === 'tag'" :type="getTagType(row[col.key], col.tagConfig)"
                        :size="col.tagSize || 'small'" :effect="col.tagEffect || 'light'">
                        {{ row[col.key] }}
                    </el-tag>
                    <!-- 链接类型 -->
                    <el-link v-else-if="col.type === 'link'" :type="col.linkType || 'primary'"
                        :underline="col.underline !== false" @click="handleLinkClick(row, col, $index)">
                        {{ row[col.key] }}
                    </el-link>
                    <!-- 图片类型 -->
                    <el-image v-else-if="col.type === 'image'" :src="row[col.key]" :alt="col.imageAlt || ''"
                        :fit="col.imageFit || 'cover'"
                        :style="{ width: col.imageWidth || '40px', height: col.imageHeight || '40px' }"
                        :preview-src-list="col.imagePreview ? [row[col.key]] : undefined" />
                    <!-- 开关类型 -->
                    <el-switch v-else-if="col.type === 'switch'" v-model="row[col.key]" :disabled="col.disabled"
                        @change="handleSwitchChange(row, col, $index)" />
                    <!-- 进度条类型 -->
                    <el-progress v-else-if="col.type === 'progress'" :percentage="row[col.key]"
                        :color="col.progressColor" :stroke-width="col.strokeWidth || 6" :text-inside="col.textInside" />
                    <!-- 默认文本 -->
                    <span v-else>{{ row[col.key] }}</span>
                </template>
            </el-table-column>

            <!-- 操作列 -->
            <el-table-column v-if="actions && actions.length > 0" label="操作" :width="actionColumnWidth"
                :fixed="actionColumnFixed" align="center">
                <template #default="{ row, $index }">
                    <el-button v-for="action in actions" :key="action.key" :type="action.type || 'primary'"
                        :size="action.size || 'small'" :plain="action.plain" :round="action.round"
                        :circle="action.circle" :disabled="action.disabled && action.disabled(row)"
                        @click="handleAction(action, row, $index)">
                        {{ action.label }}
                    </el-button>
                </template>
            </el-table-column>
        </el-table>

        <!-- 分页器 -->
        <div v-if="showPagination" class="pagination-container">
            <el-pagination :current-page="currentPage" :page-size="pageSize" :page-sizes="pageSizes" :total="total"
                :layout="paginationLayout" :background="paginationBackground" @size-change="handleSizeChange"
                @current-change="handleCurrentChange" />
        </div>


    </div>
</template>

<script setup>
import { ref, computed, h } from "vue";

// Props 定义
const props = defineProps({
    // 基础配置
    columns: { type: Array, required: true },
    data: { type: Array, required: true },
    loading: { type: Boolean, default: false },

    // 表格样式
    height: { type: [String, Number], default: undefined },
    maxHeight: { type: [String, Number], default: undefined },
    stripe: { type: Boolean, default: false },
    border: { type: Boolean, default: true },
    size: { type: String, default: 'default' },

    // 功能配置
    showSelection: { type: Boolean, default: false },
    showIndex: { type: Boolean, default: false },
    showPagination: { type: Boolean, default: false },

    // 操作配置
    actions: { type: Array, default: () => [] },
    actionColumnWidth: { type: [String, Number], default: 150 },
    actionColumnFixed: { type: [String, Boolean], default: 'right' },

    // 分页配置
    currentPage: { type: Number, default: 1 },
    pageSize: { type: Number, default: 10 },
    pageSizes: { type: Array, default: () => [10, 20, 50, 100] },
    total: { type: Number, default: 0 },
    paginationLayout: { type: String, default: 'total, sizes, prev, pager, next, jumper' },
    paginationBackground: { type: Boolean, default: true },

    // 样式配置
    headerCellStyle: { type: Object, default: () => ({}) },
    cellStyle: { type: Object, default: () => ({}) },
});

// Emits 定义
const emit = defineEmits([
    'sort-change',
    'filter-change',
    'selection-change',
    'row-click',
    'row-dblclick',
    'action',
    'size-change',
    'current-change',
    'link-click',
    'switch-change'
]);

// 响应式数据
const tableRef = ref(null);
const sortConfig = ref({});
const dateRangeFilters = ref({});
const filterTrigger = ref(0); // 用于触发筛选重新计算

// 计算属性
const computedColumns = computed(() => {
    return props.columns.map(col => ({
        ...col,
        // 兼容 label 和 title 属性
        label: col.label || col.title,
    }));
});

const filteredData = computed(() => {
    // 依赖 filterTrigger 来触发重新计算
    filterTrigger.value;

    let result = [...props.data];

    // 应用日期范围筛选
    result = result.filter(row => {
        return computedColumns.value.every(col => {
            if (col.type === 'date' || col.type === 'datetime') {
                const dateRange = dateRangeFilters.value[col.key];
                if (!dateRange || !dateRange.length) return true;

                const rowDateStr = row[col.key];
                let rowDate;

                if (rowDateStr.includes(' ')) {
                    // 格式：'2023-01-15 16:30:00' -> '2023-01-15'
                    rowDate = new Date(rowDateStr.split(' ')[0]);
                } else {
                    // 格式：'2023-01-15' 或 ISO格式
                    rowDate = new Date(rowDateStr);
                }

                const startDate = new Date(dateRange[0]);
                const endDate = new Date(dateRange[1]);

                // 设置时间为当天的开始和结束
                startDate.setHours(0, 0, 0, 0);
                endDate.setHours(23, 59, 59, 999);

                const isInRange = rowDate >= startDate && rowDate <= endDate;

                console.log('📅 日期范围筛选检查:', {
                    column: col.key,
                    rowDate: rowDateStr,
                    startDate: startDate.toISOString(),
                    endDate: endDate.toISOString(),
                    isInRange: isInRange
                });

                return isInRange;
            }
            return true;
        });
    });

    // 应用排序
    if (sortConfig.value.prop) {
        result.sort((a, b) => {
            const aVal = a[sortConfig.value.prop];
            const bVal = b[sortConfig.value.prop];

            if (sortConfig.value.order === 'ascending') {
                return aVal > bVal ? 1 : -1;
            } else if (sortConfig.value.order === 'descending') {
                return aVal < bVal ? 1 : -1;
            }
            return 0;
        });
    }

    console.log('📊 筛选结果统计:', {
        originalCount: props.data.length,
        filteredCount: result.length,
        dateRangeFilters: dateRangeFilters.value
    });

    return result;
});

// 方法定义
const getFilterOptions = (col) => {
    let options = [];

    if (col.type === 'string' || col.type === 'tag') {
        const uniqueValues = [...new Set(props.data.map(row => row[col.key]))];
        options = uniqueValues.map(value => ({ text: value, value }));
    } else if (col.type === 'date' || col.type === 'datetime') {
        // 日期类型：生成日期筛选选项
        const uniqueDates = [...new Set(props.data.map(row => {
            const dateStr = row[col.key];
            // 处理不同的日期格式
            if (dateStr.includes(' ')) {
                // 格式：'2023-01-15 16:30:00' -> '2023-01-15'
                return dateStr.split(' ')[0];
            } else {
                // 格式：'2023-01-15' 或 ISO格式
                const date = new Date(dateStr);
                return date.toISOString().split('T')[0];
            }
        }))];
        options = uniqueDates.sort().map(date => ({ text: date, value: date }));
    }

    // 打印筛选选项信息
    console.log(`📋 列 "${col.label || col.title}" 筛选选项:`, {
        columnKey: col.key,
        columnType: col.type,
        optionsCount: options.length,
        options: options
    });

    return options;
};

const getFilterMethod = (col) => {
    return (value, row) => {
        let result = false;

        if (col.type === 'date' || col.type === 'datetime') {
            // 日期类型：比较日期部分
            const rowDateStr = row[col.key];
            let rowDate;

            if (rowDateStr.includes(' ')) {
                // 格式：'2023-01-15 16:30:00' -> '2023-01-15'
                rowDate = rowDateStr.split(' ')[0];
            } else {
                // 格式：'2023-01-15' 或 ISO格式
                rowDate = new Date(rowDateStr).toISOString().split('T')[0];
            }

            result = rowDate === value;
        } else {
            // 字符串和标签类型：直接比较
            result = row[col.key] === value;
        }

        // 打印筛选匹配信息
        console.log(`🔍 筛选匹配:`, {
            column: col.label || col.title,
            filterValue: value,
            rowValue: row[col.key],
            match: result,
            rowData: row
        });

        return result;
    };
};

// 日期筛选面板
const getDateFilterPanel = (col) => {
    return {
        render: () => {
            return h('div', { class: 'date-filter-panel' }, [
                h('div', { class: 'filter-tips' }, [
                    h('el-icon', { class: 'el-icon-info' }),
                    h('span', '选择日期范围进行筛选')
                ]),
                h('el-date-picker', {
                    modelValue: dateRangeFilters.value[col.key],
                    'onUpdate:modelValue': (value) => {
                        dateRangeFilters.value[col.key] = value;
                        handleDateRangeFilterChange(col.key);
                    },
                    type: 'daterange',
                    'range-separator': '至',
                    'start-placeholder': '开始日期',
                    'end-placeholder': '结束日期',
                    size: 'small',
                    clearable: true,
                    class: 'date-picker-full'
                }),
                h('div', { class: 'filter-actions' }, [
                    h('el-button', {
                        size: 'small',
                        type: 'primary',
                        onClick: () => applyDateRangeFilter(col.key)
                    }, '应用筛选'),
                    h('el-button', {
                        size: 'small',
                        onClick: () => clearDateRangeFilter(col.key)
                    }, '清空')
                ])
            ]);
        }
    };
};

const getTagType = (value, tagConfig) => {
    if (tagConfig && tagConfig.typeMap) {
        return tagConfig.typeMap[value] || 'info';
    }
    return 'info';
};

const uniqueValues = (key) => {
    return [...new Set(props.data.map(row => row[key]))];
};

// 事件处理
const handleSortChange = ({ prop, order }) => {
    sortConfig.value = { prop, order };
    emit('sort-change', { prop, order });
};

const handleFilterChange = (filters) => {
    console.log('🔍 筛选触发/收起:', {
        timestamp: new Date().toLocaleString(),
        filters: filters,
        filterCount: Object.keys(filters).length,
        activeFilters: Object.entries(filters).filter(([key, value]) => value && value.length > 0),
        tableData: props.data.length,
        filteredData: filteredData.value.length
    });
    emit('filter-change', filters);
};

const handleSelectionChange = (selection) => {
    emit('selection-change', selection);
};

const handleRowClick = (row, column, event) => {
    emit('row-click', row, column, event);
};

const handleRowDblClick = (row, column, event) => {
    emit('row-dblclick', row, column, event);
};

const handleAction = (action, row, index) => {
    if (action.handler) {
        action.handler(row, index);
    }
    emit('action', action.key, row, index);
};

const handleLinkClick = (row, col, index) => {
    emit('link-click', row, col, index);
};

const handleSwitchChange = (row, col, index) => {
    emit('switch-change', row, col, index);
};

const handleSizeChange = (size) => {
    emit('size-change', size);
};

const handleCurrentChange = (page) => {
    emit('current-change', page);
};

// 日期范围筛选相关方法
const handleDateRangeFilterChange = (columnKey) => {
    console.log('📅 日期范围筛选变化:', {
        column: columnKey,
        dateRange: dateRangeFilters.value[columnKey],
        timestamp: new Date().toLocaleString()
    });
    // 触发筛选重新计算
    filterTrigger.value++;
};

const applyDateRangeFilter = (columnKey) => {
    const dateRange = dateRangeFilters.value[columnKey];
    if (dateRange && dateRange.length === 2) {
        console.log('✅ 应用日期范围筛选:', {
            column: columnKey,
            startDate: dateRange[0],
            endDate: dateRange[1]
        });
        // 触发筛选重新计算
        filterTrigger.value++;
        emit('date-range-filter', {
            column: columnKey,
            startDate: dateRange[0],
            endDate: dateRange[1]
        });
    }
};

const clearDateRangeFilter = (columnKey) => {
    dateRangeFilters.value[columnKey] = null;
    console.log('🗑️ 清空日期范围筛选:', {
        column: columnKey,
        timestamp: new Date().toLocaleString()
    });
    // 触发筛选重新计算
    filterTrigger.value++;
    emit('date-range-filter', {
        column: columnKey,
        startDate: null,
        endDate: null
    });
};


// 筛选相关方法



// 暴露方法给父组件
defineExpose({
    clearSelection: () => tableRef.value?.clearSelection(),
    toggleRowSelection: (row, selected) => tableRef.value?.toggleRowSelection(row, selected),
    toggleAllSelection: () => tableRef.value?.toggleAllSelection(),
    setCurrentRow: (row) => tableRef.value?.setCurrentRow(row),
    clearSort: () => tableRef.value?.clearSort(),
    clearFilter: (columnKey) => tableRef.value?.clearFilter(columnKey),
    doLayout: () => tableRef.value?.doLayout(),
    sort: (prop, order) => tableRef.value?.sort(prop, order),
});
</script>

<style scoped>
.smart-table-container {
    width: 100%;
}

.pagination-container {
    display: flex;
    justify-content: flex-end;
    margin-top: 16px;
    padding: 0 16px;
}

.filter-content {
    padding: 20px;
}

.filter-actions {
    display: flex;
    justify-content: flex-end;
    gap: 12px;
    margin-top: 24px;
    padding-top: 16px;
    border-top: 1px solid #ebeef5;
}

/* 自定义表格样式 */
:deep(.el-table) {
    border-radius: 8px;
    overflow: hidden;
}

:deep(.el-table__header) {
    background-color: #fafafa;
}

:deep(.el-table__header th) {
    background-color: #fafafa;
    font-weight: 600;
    color: #303133;
}

:deep(.el-table__body tr:hover > td) {
    background-color: #f5f7fa;
}

/* 筛选按钮样式 */
:deep(.el-table__column-filter-trigger) {
    color: #909399;
    transition: color 0.3s;
}

:deep(.el-table__column-filter-trigger:hover) {
    color: #409eff;
}


/* 日期筛选面板样式 */
.date-filter-panel {
    padding: 12px;
    min-width: 300px;
    background: #fff;
    border-radius: 4px;
    box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.1);
}

.filter-tips {
    display: flex;
    align-items: center;
    gap: 8px;
    margin-bottom: 12px;
    padding: 8px 12px;
    background-color: #f0f9ff;
    border: 1px solid #b3d8ff;
    border-radius: 4px;
    color: #1890ff;
    font-size: 12px;
}

.filter-tips .el-icon {
    font-size: 14px;
}

.date-picker-full {
    width: 100%;
    margin-bottom: 12px;
}

.filter-actions {
    display: flex;
    justify-content: flex-end;
    gap: 8px;
}

.filter-actions .el-button {
    font-size: 12px;
    padding: 4px 12px;
}

/* 操作按钮样式 */
:deep(.el-button + .el-button) {
    margin-left: 8px;
}

/* 标签样式优化 */
:deep(.el-tag) {
    border-radius: 4px;
    font-size: 12px;
}

/* 图片样式 */
:deep(.el-image) {
    border-radius: 4px;
    border: 1px solid #ebeef5;
}

/* 进度条样式 */
:deep(.el-progress) {
    width: 100%;
}

/* 开关样式 */
:deep(.el-switch) {
    --el-switch-on-color: #409eff;
    --el-switch-off-color: #c0c4cc;
}

/* 响应式设计 */
@media (max-width: 768px) {
    .pagination-container {
        justify-content: center;
        padding: 0 8px;
    }

    .filter-content {
        padding: 16px;
    }

    .filter-actions {
        flex-direction: column;
        gap: 8px;
    }

    .filter-actions .el-button {
        width: 100%;
    }
}

/* 深色模式支持 */
@media (prefers-color-scheme: dark) {
    :deep(.el-table__header) {
        background-color: #1d1e1f;
    }

    :deep(.el-table__header th) {
        background-color: #1d1e1f;
        color: #e5eaf3;
    }

    :deep(.el-table__body tr:hover > td) {
        background-color: #2d2d2d;
    }
}
</style>
